﻿using System;
using System.Data;

using Uber.Storage;

namespace Uber.HabboHotel.Misc // ALTIJD MEE VERANDEREN.
{
    /// <summary>
    /// Item ID Generator - Replaces the database id generator
    /// </summary>
    /// 
    class IdGenerator
    {
        private uint PET_SAFE_ID;

        private uint ItemId;
        private uint PetId;

        private uint UserId;
        private DateTime LastUpdated;

        private readonly Object _lock = new Object();

        public uint GetItemId()
        {
            lock (_lock)
            {
                this.ItemId++;
                return ItemId;
            }
        }

        public uint GetPetId()
        {
            lock (_lock)
            {
                this.PetId++;
                return PetId;
            }
        }

        private uint GetHighestPetId()
        {
            return PetId; // lock not needed because we're not changing any values..
        }

        private uint GetHighestUserId()
        {
            return UserId; // lock not needed because we're not changing any values..
        }

        public IdGenerator()
        {
            this.PET_SAFE_ID = 493895;
            this.ItemId = 0;
            this.PetId = 6000; // this must be enough.
            this.UserId = 0;
        }

        public Boolean NeedsUpdate
        {
            get
            {
                TimeSpan Diff = (DateTime.Now - LastUpdated);

                return ((Diff.Hours * 60) + (Diff.Minutes) >= 10);
            }
        }

        public void Initialize()
        {
            using (DatabaseClient dbClient = UberEnvironment.GetDatabase().GetClient())
            {
                try
                {
                    ItemId = (uint)dbClient.ReadDataRow("SELECT MAX(id) FROM items LIMIT 1")[0];
                    PetId = (uint)dbClient.ReadDataRow("SELECT MAX(id) FROM user_pets LIMIT 1")[0];
                    UserId = (uint)dbClient.ReadDataRow("SELECT MAX(id) FROM users LIMIT 1")[0];
                }
                catch (InvalidCastException) { }
            }

            if (GetHighestUserId() > GetHighestPetId())
            {
                PetId = PetId + PET_SAFE_ID;
            }

            UberEnvironment.GetLogging().WriteLine("Highest IDs Generated: ItemId[" + ItemId + "], PetId[" + PetId + "] !");

            LastUpdated = DateTime.Now;
        }
    }
}
